<template>
  <el-dialog
      top="10vh"
      width="900px"
      title="选择入围供应商"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="supplier-selection">
      <div class="bidding-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="比价月份">{{ currentBidding?.month }}</el-descriptions-item>
          <el-descriptions-item label="比价标题">{{ currentBidding?.title }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="supplier-list">
        <h4>参与竞标的供应商</h4>
        <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            :data="supplierData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
        >
          <el-table-column prop="supplier_name" label="供应商名称" width="180"/>
          <el-table-column prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="info">参与竞标</el-tag>
              <el-tag v-if="scope.row.status === 2" type="warning">已提交报价</el-tag>
              <el-tag v-if="scope.row.status === 3" type="success">已入围</el-tag>
              <el-tag v-if="scope.row.status === 4" type="danger">未入围</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="submit_time" label="报价提交时间" width="180">
            <template slot-scope="scope">
              <span v-if="scope.row.submit_time">{{ scope.row.submit_time }}</span>
              <span v-else style="color: #999;">未提交</span>
            </template>
          </el-table-column>
          <el-table-column prop="total_dishes" label="报价菜品数" width="100"/>
          <el-table-column prop="avg_price_diff" label="平均价格差异" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.avg_price_diff > 0" style="color: #F56C6C;">
                +¥{{ scope.row.avg_price_diff }}
              </span>
              <span v-else-if="scope.row.avg_price_diff < 0" style="color: #67C23A;">
                ¥{{ scope.row.avg_price_diff }}
              </span>
              <span v-else style="color: #909399;">
                ¥0
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="avg_diff_percent" label="平均差异比例" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.avg_diff_percent > 0" style="color: #F56C6C;">
                +{{ scope.row.avg_diff_percent }}%
              </span>
              <span v-else-if="scope.row.avg_diff_percent < 0" style="color: #67C23A;">
                {{ scope.row.avg_diff_percent }}%
              </span>
              <span v-else style="color: #909399;">
                0%
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
              <span v-else style="color: #999;">无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="selectSupplier(scope.row)"
                :disabled="scope.row.status === 4 || selectedSupplierId === scope.row.supplier_id"
              >
                {{ selectedSupplierId === scope.row.supplier_id ? '已选择' : '选择' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogValue = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection" :disabled="!selectedSupplierId">
        确认选择
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { http } from '@/api';

export default {
  name: 'SelectSupplier',
  data() {
    return {
      dialogValue: false,
      loading: false,
      supplierData: [],
      selectedSupplierId: null,
      currentBidding: null
    };
  },
  methods: {
    open(bidding) {
      this.currentBidding = bidding;
      this.selectedSupplierId = null;
      this.dialogValue = true;
      this.loadSupplierData();
    },
    loadSupplierData() {
      if (!this.currentBidding) return;

      this.loading = true;
      // 先获取参与竞标的供应商列表
      http.biddingSupplier.list({
        monthly_bidding_id: this.currentBidding.id
      }).then(res => {
        const biddingSuppliers = res.data;

        // 获取供应商报价数据
        return http.supplierQuote.list({
          monthly_bidding_id: this.currentBidding.id
        }).then(quoteRes => {
          // 按供应商分组统计报价数据
          const quoteMap = {};
          quoteRes.data.forEach(item => {
            if (!quoteMap[item.supplier_id]) {
              quoteMap[item.supplier_id] = {
                quotes: []
              };
            }
            quoteMap[item.supplier_id].quotes.push(item);
          });

          // 合并数据
          this.supplierData = biddingSuppliers.map(biddingSupplier => {
            const quotes = quoteMap[biddingSupplier.supplier_id]?.quotes || [];
            const totalDishes = quotes.length;

            let avgPriceDiff = 0;
            let avgDiffPercent = 0;

            if (totalDishes > 0) {
              const totalDiff = quotes.reduce((sum, quote) => {
                return sum + (quote.quoted_price - quote.base_price);
              }, 0);
              avgPriceDiff = (totalDiff / totalDishes).toFixed(2);

              const totalDiffPercent = quotes.reduce((sum, quote) => {
                const diff = quote.quoted_price - quote.base_price;
                const percent = quote.base_price > 0 ? (diff / quote.base_price) * 100 : 0;
                return sum + percent;
              }, 0);
              avgDiffPercent = (totalDiffPercent / totalDishes).toFixed(2);
            }

            return {
              ...biddingSupplier,
              total_dishes: totalDishes,
              avg_price_diff: avgPriceDiff,
              avg_diff_percent: avgDiffPercent
            };
          });

          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    selectSupplier(supplier) {
      this.selectedSupplierId = supplier.supplier_id;
    },
    confirmSelection() {
      if (!this.selectedSupplierId || !this.currentBidding) return;

      // 更新比价记录，选择入围供应商
      http.monthlyBidding.update(this.currentBidding.id, {
        selected_supplier_id: this.selectedSupplierId,
        status: 3 // 已确定供应商
      }).then(() => {
        // 更新所有供应商的状态
        const updatePromises = this.supplierData.map(supplier => {
          const newStatus = supplier.supplier_id === this.selectedSupplierId ? 3 : 4;
          return http.biddingSupplier.update(supplier.id, {
            status: newStatus,
            remark: supplier.supplier_id === this.selectedSupplierId ? '已入围' : '未入围'
          });
        });

        return Promise.all(updatePromises);
      }).then(() => {
        this.$message.success('供应商选择成功');
        this.dialogValue = false;
        this.$emit('get-page');
      });
    }
  }
};
</script>

<style scoped lang="scss">
.supplier-selection {
  .bidding-info {
    margin-bottom: 20px;
  }

  .supplier-list {
    h4 {
      margin-bottom: 15px;
      color: #303133;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
